from django.shortcuts import render
from django.http import HttpResponse
from FirstBlog import models
# Create your views here.
from tkinter.messagebox import *
import tkinter
def index(request):
    articles = models.Article.objects.all()
    #return HttpResponse('hello my firstblog')
    return render(request,'firstblog/first.html',{'articles':articles})

def article_page(request,article_id):
    article = models.Article.objects.get(pk=article_id)
    return render(request,'firstblog/scend.html',{'article':article})

def edit_page(request,article_id):
    if str(article_id)=='0':
        return render(request,'firstblog/edit_page.html')
    article = models.Article.objects.get(pk=article_id)
    return render(request,'firstblog/edit_page.html',{'article':article})

def edit_response(request):
    title = request.POST['title']
    content= request.POST['content']
    #pub_time=request.POST['pub_time']
    try:
        article_id = request.POST['article_id']
        # print(article_id)
    except KeyError as e:
            print('id错误', e)
    if title !="":
        if article_id == '0':
            try:
                models.Article.objects.create(title=title,content=content)
            except:
                print('出现异常')
            articles = models.Article.objects.all()
            return render(request,'firstblog/first.html',{'articles':articles})
        article = models.Article.objects.get(pk=article_id)
        article.title = title
        article.content = content
        article.save()
        return render(request,'firstblog/scend.html',{'article':article})
    else:

        return render(request, 'firstblog/edit_page.html')

def edit_delete(request):
    try:
        article_id = request.POST['article_id']
        models.Article.objects.filter(id=article_id).delete()
        print('文章id是：',article_id)
    except KeyError as e:
        print('id错误',e)
    articles = models.Article.objects.all()
    return render(request, 'firstblog/first.html', {'articles': articles})
    # return HttpResponse("")